<template>
  <div class="lawyer-management">


    <!-- 律师列表 -->
    <el-card class="list-container" style="margin-top: 16px;">

      <div class="table-operations">
        <!-- 新增：查看所有律师绩效的按钮 -->
        <el-button type="info" @click="getAllPerformance">所有绩效</el-button>
      </div>
      <el-table
          :data="lawyerList"
          border
          stripe
          v-loading="loading"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="licenseNo" label="执业证号" />
        <el-table-column prop="specialty" label="专业领域" />
        <el-table-column prop="serviceArea" label="服务区域" />
        <el-table-column prop="yearsOfPractice" label="执业年限" width="100" />
        <el-table-column prop="successRate" label="胜诉率(%)" width="120" />
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="info" @click="handlePerformance(scope.row)">绩效</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchForm.page"
            :page-sizes="[10, 20, 50]"
            :page-size="searchForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </el-card>

    <!-- 所有律师绩效列表对话框 -->
    <el-dialog title="所有律师绩效列表" v-model="allPerformanceVisible" width="80%">
      <el-table
          :data="allPerformanceData"
          border
          stripe
          max-height="500"
          v-loading="loading"
      >
        <el-table-column prop="lawyerId" label="律师ID" width="100" />
        <el-table-column prop="lawyerName" label="律师姓名" />
        <el-table-column prop="caseCount" label="接案总量" width="100" />
        <el-table-column prop="successRate" label="胜诉率(%)" width="120" />
        <el-table-column prop="avgResponseHours" label="平均响应时间(小时)" />
        <el-table-column prop="firstCaseTime" label="首次接案时间" />
        <el-table-column prop="latestCaseTime" label="最近接案时间" />
      </el-table>
      <template #footer>
        <el-button @click="allPerformanceVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 律师详情对话框 -->
    <el-dialog title="律师详情" v-model="detailVisible" width="70%">
      <el-descriptions column="1" border>
        <el-descriptions-item label="执业证号">{{ currentLawyer.licenseNo }}</el-descriptions-item>
        <el-descriptions-item label="专业领域">{{ currentLawyer.specialty }}</el-descriptions-item>
        <el-descriptions-item label="服务区域">{{ currentLawyer.serviceArea }}</el-descriptions-item>
        <el-descriptions-item label="执业年限">{{ currentLawyer.yearsOfPractice }}年</el-descriptions-item>
        <el-descriptions-item label="胜诉率">{{ currentLawyer.successRate }}%</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentLawyer.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentLawyer.email }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ currentLawyer.idCard }}</el-descriptions-item>
        <el-descriptions-item label="个人简介">{{ currentLawyer.introduction }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <img
              v-if="currentLawyer.avatar"
              :src="currentLawyer.avatar"
              class="avatar"
              alt="头像"
          >
          <span v-else>未上传</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAssignCase">分配案件</el-button>
      </template>
    </el-dialog>

    <!-- 编辑律师信息对话框 -->
    <el-dialog title="编辑律师信息" v-model="editVisible" width="70%">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <el-form-item label="执业证号" prop="licenseNo">
          <el-input v-model="editForm.licenseNo" />
        </el-form-item>
        <el-form-item label="专业领域" prop="specialty">
          <el-input v-model="editForm.specialty" />
        </el-form-item>
        <el-form-item label="服务区域" prop="serviceArea">
          <el-input v-model="editForm.serviceArea" />
        </el-form-item>
        <el-form-item label="执业年限" prop="yearsOfPractice">
          <el-input v-model.number="editForm.yearsOfPractice" type="number" min="1" />
        </el-form-item>
        <el-form-item label="胜诉率(%)" prop="successRate">
          <el-input v-model.number="editForm.successRate" type="number" min="0" max="100" />
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input v-model="editForm.introduction" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核律师证书" v-model="auditVisible" width="50%">
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio label="APPROVED">通过</el-radio>
            <el-radio label="REJECTED">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            label="拒绝原因"
            prop="rejectReason"
            v-if="auditForm.auditResult === 'REJECTED'"
        >
          <el-input v-model="auditForm.rejectReason" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitAudit"
            :loading="loading"
        >
        提交审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 绩效详情对话框 -->
    <el-dialog title="律师绩效" v-model="performanceVisible" width="60%">
      <el-card v-if="performanceData">
        <el-descriptions column="2" border>
          <el-descriptions-item label="接案总量">{{ performanceData.caseCount }}</el-descriptions-item>
          <el-descriptions-item label="胜诉率">{{ performanceData.successRate }}%</el-descriptions-item>
          <el-descriptions-item label="平均响应时间(小时)">{{ performanceData.avgResponseHours }}</el-descriptions-item>
          <el-descriptions-item label="首次接案时间">{{ performanceData.firstCaseTime }}</el-descriptions-item>
          <el-descriptions-item label="最近接案时间" span="2">{{ performanceData.latestCaseTime }}</el-descriptions-item>
        </el-descriptions>

        <el-table
            :data="performanceData.caseList"
            border
            style="margin-top: 16px;"
            max-height="300"
        >
          <el-table-column prop="caseId" label="案件ID" />
          <el-table-column prop="caseName" label="案件名称" />
          <el-table-column prop="handlingTime" label="处理时间" />
        </el-table>
      </el-card>
      <template #footer>
        <el-button @click="performanceVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 分配案件对话框 -->
    <el-dialog title="分配案件给律师" v-model="assignVisible" width="50%">
      <el-form :model="assignForm" :rules="assignRules" ref="assignFormRef" label-width="100px">
        <el-form-item label="案件ID" prop="caseId">
          <el-input v-model.number="assignForm.caseId" />
        </el-form-item>
        <el-form-item label="分配原因" prop="assignReason">
          <el-input v-model="assignForm.assignReason" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAssign">确认分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { LawyerApi } from '@/api/lawyer'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单（匹配LawyerSearchDTO）
const searchForm = reactive({
  specialty: '',
  serviceArea: '',
  minYears: null,
  minSuccessRate: null,
  page: 1,
  pageSize: 10
})

// 所有律师绩效数据
const allPerformanceData = ref([])
// 所有律师绩效对话框状态
const allPerformanceVisible = ref(false)
// 获取所有律师绩效列表
const getAllPerformance = async () => {
  try {
    loading.value = true
    const response = await LawyerApi.listPerformance()
    allPerformanceData.value = response.data || [] // 存储所有律师绩效数据
    allPerformanceVisible.value = true // 显示对话框
  } catch (error) {
    console.error('获取所有律师绩效失败:', error)
    ElMessage.error('获取所有律师绩效失败')
  } finally {
    loading.value = false
  }
}

// 律师列表数据
const lawyerList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedLawyers = ref([])

// 对话框状态
const detailVisible = ref(false)
const editVisible = ref(false)
const auditVisible = ref(false)
const performanceVisible = ref(false)
const assignVisible = ref(false)

// 当前操作的律师
const currentLawyer = ref({})

// 编辑表单数据（匹配LawyerInfoDTO）
const editForm = reactive({
  id: '',
  licenseNo: '',
  specialty: '',
  serviceArea: '',
  yearsOfPractice: 0,
  introduction: '',
  successRate: 0
})

// 审核表单数据（匹配LawyerAuditDTO）
const auditForm = reactive({
  id: '',
  auditResult: 'APPROVED',
  rejectReason: ''
})

// 绩效数据（匹配LawyerPerformanceDTO）
const performanceData = ref(null)

// 分配案件表单（匹配CaseAssignDTO）
const assignForm = reactive({
  lawyerId: '',
  caseId: null,
  assignReason: ''
})

// 表单验证规则
const editRules = reactive({
  licenseNo: [{ required: true, message: '请输入律师执照号', trigger: 'blur' }],
  specialty: [{ required: true, message: '请输入专业领域', trigger: 'blur' }],
  serviceArea: [{ required: true, message: '请输入服务区域', trigger: 'blur' }],
  yearsOfPractice: [
    { required: true, message: '请输入执业年限', trigger: 'blur' },
    { type: 'number', min: 1, message: '执业年限必须为正数', trigger: 'blur' }
  ],
  successRate: [
    { type: 'number', min: 0, max: 100, message: '胜诉率必须在0-100之间', trigger: 'blur' }
  ]
})

const auditRules = reactive({
  auditResult: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [
    { required: true, message: '请输入拒绝原因', trigger: 'blur' },
    { min: 5, message: '拒绝原因至少5个字符', trigger: 'blur' }
  ]
})

const assignRules = reactive({
  caseId: [
    { required: true, message: '请输入案件ID', trigger: 'blur' },
    { type: 'number', message: '案件ID必须为数字', trigger: 'blur' }
  ],
  assignReason: [
    { min: 0, max: 500, message: '分配原因不能超过500字', trigger: 'blur' }
  ]
})

// 表单引用
const editFormRef = ref(null)
const auditFormRef = ref(null)
const assignFormRef = ref(null)

// 页面加载时获取律师列表
onMounted(() => {
  getLawyerList()
})

// 获取律师列表
const getLawyerList = async () => {
  try {
    loading.value = true
    const response = await LawyerApi.searchLawyers(searchForm)
    lawyerList.value = response.data.records || response.data
    total.value = response.data.total || lawyerList.value.length
  } catch (error) {
    console.error('获取律师列表失败:', error)
    ElMessage.error('获取律师列表失败')
  } finally {
    loading.value = false
  }
}

// 分页事件
const handleSizeChange = (size) => {
  searchForm.pageSize = size
  getLawyerList()
}

const handleCurrentChange = (page) => {
  searchForm.page = page
  getLawyerList()
}

// 选择事件
const handleSelectionChange = (val) => {
  selectedLawyers.value = val
}

// 查看详情
const handleView = async (lawyer) => {
  try {
    loading.value = true
    const response = await LawyerApi.getLawyerInfo(lawyer.id)
    currentLawyer.value = response.data
    detailVisible.value = true
  } catch (error) {
    console.error('获取律师详情失败:', error)
    ElMessage.error('获取律师详情失败')
  } finally {
    loading.value = false
  }
}

// 编辑律师
const handleEdit = async (lawyer) => {
  try {
    loading.value = true
    const response = await LawyerApi.getLawyerInfo(lawyer.id)
    const lawyerData = response.data
    Object.assign(editForm, {
      id: lawyerData.id,
      licenseNo: lawyerData.licenseNo,
      specialty: lawyerData.specialty,
      serviceArea: lawyerData.serviceArea,
      yearsOfPractice: lawyerData.yearsOfPractice,
      introduction: lawyerData.introduction,
      successRate: lawyerData.successRate
    })
    editVisible.value = true
  } catch (error) {
    console.error('获取律师详情失败:', error)
    ElMessage.error('获取律师详情失败')
  } finally {
    loading.value = false
  }
}

// 提交编辑
const submitEdit = async () => {
  try {
    await editFormRef.value.validate()
    await LawyerApi.updateLawyerInfo(editForm)
    ElMessage.success('律师信息更新成功')
    editVisible.value = false
    getLawyerList()
  } catch (error) {
    console.error('更新律师信息失败:', error)
    if (error.name !== 'Error') {
      ElMessage.error('请完善表单信息')
    }
  }
}

// 审核操作
const handleAudit = (lawyer) => {
  // 重置表单数据
  auditForm.id = lawyer.id
  auditForm.auditResult = 'APPROVED'
  auditForm.rejectReason = ''
  // 重置表单验证状态
  if (auditFormRef.value) {
    auditFormRef.value.clearValidate()
  }
  auditVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  try {
    // 审核操作二次确认
    await ElMessageBox.confirm(
        `确定要${auditForm.auditResult === 'APPROVED' ? '通过' : '拒绝'}该律师的审核吗？`,
        '审核确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    loading.value = true // 显示加载状态
    await auditFormRef.value.validate()
    await LawyerApi.auditCertificate(auditForm)
    ElMessage.success('审核操作成功')
    auditVisible.value = false
    getLawyerList() // 刷新列表
  } catch (error) {
    // 忽略取消确认的错误
    if (error.name !== 'Cancel') {
      console.error('审核操作失败:', error)
      if (error.name !== 'Error') {
        ElMessage.error('请完善审核信息')
      }
    }
  } finally {
    loading.value = false // 关闭加载状态
  }
}

// 查看绩效
const handlePerformance = async (lawyer) => {
  try {
    loading.value = true
    const response = await LawyerApi.getPerformance(lawyer.id)
    performanceData.value = response.data
    performanceVisible.value = true
  } catch (error) {
    console.error('获取律师绩效失败:', error)
    ElMessage.error('获取律师绩效失败')
  } finally {
    loading.value = false
  }
}

// 分配案件
const handleAssignCase = () => {
  assignForm.lawyerId = currentLawyer.value.id
  assignForm.caseId = null
  assignForm.assignReason = ''
  assignVisible.value = true
}

// 提交案件分配
const submitAssign = async () => {
  try {
    await assignFormRef.value.validate()
    await LawyerApi.assignCaseToLawyer(assignForm)
    ElMessage.success('案件分配成功')
    assignVisible.value = false
  } catch (error) {
    console.error('案件分配失败:', error)
    if (error.name !== 'Error') {
      ElMessage.error('请输入案件ID')
    }
  }
}

// 新增律师（跳转到注册页面或显示注册表单）
const showAddDialog = () => {
  // 实际项目中可能需要跳转到注册页面
  // 这里简单处理为提示
  ElMessage.info('请从律师注册入口进行新增操作')
  // 示例: router.push('/lawyer/register')
}
</script>

<style scoped>
.lawyer-management {
  padding: 20px;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style>